<template>
  <view v-if="postDetail" class="content">
    <view v-if="postDetail.videoId" class="video-wrap">
      <view class="video-box">
        <view class="video">
          <ali-player
            v-if="postDetail.video && postDetail.playauth"
            :vid="postDetail.video"
            :playauth="postDetail.playauth"
            :previewPic="postDetail.cover"></ali-player>
        </view>
      </view>
    </view>
    <view v-else class="cover">
      <img
        v-if="postDetail.imgUrl"
        class="image"
        :src="postDetail.imgUrl"
        :alt="postDetail.title" />
    </view>

    <view class="padding-l-r-10">
      <h3 class="title item-text">
        {{ postDetail.title }}
      </h3>

      <view class="time-text flex items-center justify-between">
        <text class="time">日期：{{ postDetail.updateTime }}</text>
        <view class="view-num">
          <text class="dyicon icon-liulanliang"></text>
          <text>{{ postDetail.clickCount || 0 }}</text>
        </view>
      </view>

      <view v-if="postDetail.description" class="abstract">
        <text>{{ postDetail.description }}</text>
      </view>

      <view class="item-text desc" v-html="postDetail.context"></view>
    </view>

    <view style="width: 100%; height: 90rpx"></view>

    <view
      v-if="isUniapp"
      class="to-home"
      :style="`background: ${config.configJson.config.teacherResources.theme};`"
      @click="backHome('/pages/index/index')"
      >首页</view
    >

    <WxOpenApp v-if="!isUniapp && config" :extinfo="extinfo"></WxOpenApp>
  </view>
</template>

<script>
  import { mapGetters } from 'vuex';
  import * as Api from '@/server/index.js';
  import * as Utils from '@/utils/index.js';
  import * as Constant from '@/constant/index.js';
  import WxOpenApp from '@/components/WxOpenApp.vue';
  import aliPlayer from '@/components/aliplayer/aliplayer.vue';

  const isUniapp = Utils.util.isUniapp();

  export default {
    components: {
      WxOpenApp,
      aliPlayer,
    },
    data() {
      return {
        options: null,
        isRender: false,
        isUniapp: isUniapp,
        ativeInfo: null,
        config: null,
        configJson: {},
        postDetail: null, // 帖子信息
        video: null,
        likeMask: false,
        shareUrl: '',
        extinfo: '',
      };
    },

    computed: {
      ...mapGetters(['token']),
    },

    async onLoad(options) {
      this.options = options;
      this.shareUrl = `https://wap2.wxls.pro/${
        Constant.ROUTER_BASE
      }/?t=${new Date().getTime()}#/pages/index/detail?id=${options.id}&t=${new Date().getTime()}`;
      await this.$onLaunched;
      await this.getPost();
      isUniapp && this.initLoad();
      this.config = this.$store.state.config;

      this.isWxH5() && this.handleExtinfo();
      this.isWxH5() && this.wxInit();

      this.postDetail && (await this.getVideoUrl());
    },
    onShow() {
      if (window.h5uni && this.isRender) {
        h5uni.postMessage({
          data: {
            share: this.share,
          },
        });
      }
    },

    methods: {
      // 页面初始化
      initLoad() {
        const config = this.$store.state.config;
        try {
          // TODO 分享配置
          this.share = {
            strShareId: config.code,
            strClassId: 'wxlsvote',
            strClassName: '我正在参加' + config.shareTitle,
            title: '我正在参加' + config.shareTitle,
            thumb: config.sharePicture + '?x-oss-process=image/resize,w_250',
            summary: config.shareDescribe,
            url: `${this.shareUrl}&time=${new Date().getTime()}`, // TODO
          };
          // console.log('this.share---',JSON.stringify(this.share));
          Utils.appInteractionH5.init.init(this.options, this.share);
        } catch (e) {
          console.log('e---', e);
        }
      },

      isWxH5() {
        let iswx = false;
        let ua = navigator.userAgent.toLowerCase();
        if (/micromessenger/.test(ua)) {
          // window.location.href = this.$store.getters.config.jumpAddress;
          iswx = true;
        }
        return iswx;
      },

      async wxInit() {
        try {
          // #ifdef H5
          await Utils.wxShare.getWxApi.wxShare();
          this.get_wx_h5_share();
          // #endif
        } catch (e) {
          return Promise.reject(new Error(e));
        }
      },

      // 帖子详情
      async getPost() {
        uni.showLoading({ title: '加载中...', mask: true });
        try {
          const { data: res } = this.options.isMy
            ? await Api.index.articleDetail(this.options.id)
            : await Api.index.articleDetail(this.options.id);

          this.postDetail = res.data;
          uni.setNavigationBarTitle({
            title: `${this.postDetail.title}`,
          });
          this.isRender = true;
        } finally {
          uni.hideLoading();
        }
      },

      // 根据视频id获取阿里云视频播放凭证
      async getVideoUrl() {
        if (!this.postDetail.videoId) {
          return;
        }
        const id = this.postDetail.videoId;
        try {
          const { data: res } = await Api.index.videoPlayauth({
            videoId: id,
            authInfoTimeout: 100,
            apiVersion: '1.0.0',
          });
          if (!res.data) {
            uni.showToast({
              title: '视频转码中或失效了',
              icon: 'none',
            });
          }
          this.$set(this.postDetail, 'playauth', res.data.playAuth);
          if (!this.postDetail.cover) this.postDetail.cover = res.data.videoMeta.coverURL;
        } catch (e) {}
      },

      // 回首页
      backHome(link) {
        let url = link;
        if (this.options.wxlsToken) {
          url = `${url}?wxlsToken=${this.options.wxlsToken}&t=${new Date().getTime()}`;
        }
        Utils.pageTo.reLaunch(url);
      },
      // 判断是否登录
      checkLogin() {
        if (!this.token) {
          uni.showModal({
            title: '未登录',
            content: '您未登录，需要登录后才能继续',
            success: (res) => {
              if (res.confirm) {
                Utils.appInteractionH5.tologin.toAppLogin(this.shareUrl);
              } else if (res.cancel) {
                // Utils.pageTo.navigateBack()
              }
            },
          });
          return false;
        }
        return true;
      },

      //TODO 分享配置
      handleExtinfo() {
        const config = this.$store.state.config;
        if (this.shareUrl && !this.shareUrl.includes('http')) {
          this.extinfo = this.shareUrl;
          return;
        }
        const url = this.shareUrl ? encodeURIComponent(this.shareUrl) : '';
        const thumb = config.sharePicture;
        const title = '我正在参加' + config.shareTitle;
        const description = config.shareDescribe;
        const extraParameter =
          config.extraParameter &&
          config.extraParameter
            .split(',')
            .map((item) => `&${item}`)
            .join('');
        if (!url) return;
        this.extinfo = `/pages/webview/index?url=${url}&thumb=${thumb}?x-oss-process=image/resize,w_80&title=${title}&description=${description}${extraParameter}`;
      },

      //TODO 分享配置
      get_wx_h5_share() {
        let wx = this.wx;
        const url = `${this.shareUrl}&time=${new Date().getTime()}`;
        const config = this.$store.state.config;
        let data = {
          title: '我正在参加' + config.shareTitle,
          link: url,
          desc: config.shareDescribe,
          imgUrl: config.sharePicture + '?x-oss-process=image/resize,w_150',
        };
        // console.log('get_wx_h5_share',data)
        // ((this.options.copyfrom && this.options.copyfrom.includes('unshare')) ||
        // 	!this.postDetail.title) &&
        // 	(data = null);
        Utils.wxShare.shareApi.wx_h5_share(wx, data);
      },
    },
  };
</script>

<style lang="scss" scoped>
  page,
  body {
    min-height: 100vh;
    // background-image: linear-gradient(180deg, #fdcbcc 0%, #fff0f0 40%, #fff 80%);
  }

  .content {
    width: 10rem;
    height: 100%;
    min-height: 100vh;
    position: relative;
  }

  .padding-l-r-10 {
    padding: 0 10px;
  }

  .title {
    font-size: 18px;
    font-weight: 600;
  }

  .video-wrap {
    .video-box {
      width: 10rem;
      height: 7.493rem;
    }
    .video {
      width: 100%;
      height: 100%;
      background-color: #000;
    }
  }

  .cover {
    width: 100%;
    margin-bottom: 10px;
    .image {
      width: 100%;
      height: auto;
    }
  }

  .abstract {
    width: 100%;
    font-size: 12px;
    color: #333;
    background-color: #eee;
    padding: 20px;
    margin: 10px 0;
  }

  .time-text {
    margin-top: 8px;
    font-size: 13px;
    color: #999;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
    .time {
    }
  }

  .view-num {
    display: flex;
    align-items: flex-end;
    text {
      margin: 0 1px;
    }
  }

  .to-home {
    position: fixed;
    right: 5%;
    bottom: 15%;
    padding: 18rpx 10rpx;
    font-size: 28rpx;
    color: #fff;
    border-radius: 50%;
    z-index: 8;
  }

  .item-text {
    line-height: 1.75;
  }

  .desc {
    overflow: hidden;
    // background-color: #fff;
    padding: 20rpx 0;
    font-size: 28rpx;
    line-height: 1.75;
    // color: #aaa2a2;
    color: #333;
    img,
    p,
    span {
      max-width: 100% !important;
      height: auto !important;
    }
    p {
      margin: 28rpx 0;
    }
  }
</style>
